
package com.work.util;

import java.sql.Time;
import java.util.Locale;

import com.vaadin.data.util.converter.Converter;

public class StringToTimeConverter implements Converter<String, Time> {

	private static final long serialVersionUID = 3410252445575655118L;
	
	private static String timePattern = "([01]?[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]";
	
	@Override
	public Class<Time> getModelType()
	{
		return Time.class;
	}

	@Override
	public Class<String> getPresentationType()
	{
		return String.class;
	}

	@Override
	public Time convertToModel(String value, Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException
	{
		if (value == null || value.isEmpty()) {
			return null;
		}
		
		if (!value.matches(timePattern)) {
			throw new ConversionException();
		}
		
		return Time.valueOf(value);
	}

	@Override
	public String convertToPresentation(Time value, Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException
	{
		if (value != null) {
			return value.toString();
		}
		
		return "";
	}
	
	
}